package com.demoworld;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Set;

/**
 * Description
 * <p>
 * </p>
 * DATE 2018/5/20.
 *
 * @author liwei5.
 */
public class DemoClassPathScanner extends ClassPathBeanDefinitionScanner {
    public DemoClassPathScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
        addIncludeFilter(new AnnotationTypeFilter(Component.class));
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        printStart();
        final Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        if (beanDefinitionHolders == null || beanDefinitionHolders.isEmpty()) {
            System.out.println("no any beans found");
            this.printEnd();
            return Collections.emptySet();
        }

        beanDefinitionHolders.forEach(x -> {
            System.out.println("bean name=" + x.getBeanName() + ", class=" + x.getBeanDefinition().getBeanClassName() + " found");
        });
        this.printEnd();
        return beanDefinitionHolders;
    }

    void printStart() {
        System.out.println("========================beans start====================================");
    }

    void printEnd() {
        System.out.println("========================beans end====================================");
    }

    @Override
    protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
        return true;
    }
}
